package com.cirnoworks.utils.text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Line implements CharSequence {
	List<TextFragment> fragments = new ArrayList<TextFragment>();
	List<TextFragment> readonlyFragments = Collections
			.unmodifiableList(fragments);
	private float descent = Float.NEGATIVE_INFINITY,
			ascent = Float.NEGATIVE_INFINITY;

	public void addFragment(TextFragment fragment) {
		if (fragment.getDescent() == Float.NEGATIVE_INFINITY
				|| fragment.getAscent() == Float.NEGATIVE_INFINITY) {
			throw new RuntimeException("TextFragment not setuped");
		}
		if (descent < fragment.getDescent()) {
			descent = fragment.getDescent();
		}
		if (ascent < fragment.getAscent()) {
			ascent = fragment.getAscent();
		}
		fragments.add(fragment);
	}

	public void clearFragment() {
		descent = ascent = Float.NEGATIVE_INFINITY;
		fragments.clear();
	}

	public List<TextFragment> getFragments() {
		return readonlyFragments;
	}

	public float getDescent() {
		return descent;
	}

	public float getAscent() {
		return ascent;
	}

	public int length() {
		int length = 0;
		for (TextFragment fragment : fragments) {
			length += fragment.length();
		}
		return length;
	}

	public char charAt(int index) {
		if (index >= 0) {
			int base = 0;
			for (TextFragment fragment : fragments) {
				if (base + fragment.length() > index) {
					return fragment.charAt(index - base);
				}
				base += fragment.length();
			}
		}
		throw new IndexOutOfBoundsException(index + " / " + length());
	}

	public int fragmentsCount() {
		return fragments.size();
	}

	public CharSequence subSequence(int start, int end) {
		// TODO
		throw new IllegalStateException("No such method!");
	}

}
